from django.shortcuts import render
from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib.auth.models import User
from common.views.utils import table_api
from django.core.paginator import Paginator
from django.db.models import Q
from common.models import Logs

class LogView(View):
    @method_decorator(login_required)
    def get(self,request):
        filters = [] # 筛选条件
        page = int(request.GET.get('page'))
        limit = int(request.GET.get('limit'))
        username = request.GET.get('username')
        url = request.GET.get('url')
        if username:
            users = User.objects.filter(username__contains=username)
            users_id = [user.id for user in users]
            filters.append(Q(user_id__in=users_id))
        if url:
            filters.append(Q(url__contains=url))
        logs = Paginator(Logs.objects.filter(*filters).order_by('-ca_time'),limit).get_page(page)
        result = [{
            'id':log.id,
            'method':log.method,
            'username':LogView.get_username(log.user_id),
            'url':log.url,
            'desc':log.desc,
            'ip':log.ip,
            'success':log.success,
            'user_agent':log.user_agent,
            'ca_time':log.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
            'up_time':log.up_time.strftime('%Y-%m-%d %H:%M:%S')
        } for log in logs]
        return table_api(result=result,total=logs.paginator.count)

    @staticmethod
    def get_username(user_id):
        user = User.objects.get(id=user_id)
        return user.username